package com.example.db;

import android.support.v4.util.ArrayMap;

import com.example.db.bean.User;
import com.example.db.utils.KryoUtil;
import com.example.db.utils.TimeUtils;

import junit.framework.TestCase;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.Serializer;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentNavigableMap;

/**
 * Created by kkmike999 on 16/2/13.
 */
public class MapDbTest extends TestCase {

    public static final int    COUNT  = 10000;
    public static final String dbName = "mapdb";

    DB   db;
    File dbFile;

    User[] users;

    @Before
    public void setUp() throws Exception {
        dbFile = new File(DbApp.getContext().getCacheDir(), dbName);//File.createTempFile("mapdb","db");

//        System.out.println(dbFile.getPath());

        db = DBMaker.fileDB(dbFile)
                .closeOnJvmShutdown()
                .encryptionEnable("password")
                .make();

        users = UserHelper.createUserList(COUNT);
    }

    @After
    public void tearDown() throws Exception {
        db.close();
        dbFile.deleteOnExit();
    }

    @Test
    public void mapTest() {
        Map<String, String> map = new ArrayMap<>();

        TimeUtils.begin();

        for (User user : users) {
            map.put(user.name, KryoUtil.toString(user));
        }

        System.out.println("MapDbTest(" + users.length + ") : put Obj time = " + TimeUtils.time());
        System.out.println();
    }

    @Test
    public void mapdbPutObj() {
        Map<String, String> map = db.treeMapCreate("user_string_map1")
                .keySerializer(Serializer.STRING)
                .valueSerializer(Serializer.STRING)
                .makeOrGet();

        TimeUtils.begin();

        for (User user : users) {
            map.put(user.name, KryoUtil.toString(user));
        }

        db.commit();

        System.out.println("MapDbTest(" + users.length + ") : put Obj time = " + TimeUtils.time());
        System.out.println();
    }

    @Test
    public void halloWorld() throws IOException {
        //open an collection, TreeMap has better performance then HashMap
        ConcurrentNavigableMap<Integer, String> map = db.treeMap("collectionName");

        map.put(1, "one");
        map.put(2, "two");
        //map.keySet() is now [1,2] even before commit

        db.commit();  //persist changes into disk

        map.put(3, "three");
        //map.keySet() is now [1,2,3]
        db.rollback(); //revert recent changes
        //map.keySet() is now [1,2]

        System.out.println(map);
    }
}
